/**
 * Created by Yun on 2015-12-19.
 */

import {sequelize} from '../models';

export default class StatusError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
  toJson() {
    return {
      message: this.message,
      ...this,
    }
  }
}

StatusError.BAD_REQUEST = new StatusError(400, 'Bad Request');
StatusError.UNAUTHORIZED = new StatusError(401, 'Unauthorized');
StatusError.FORBIDDEN = new StatusError(403, 'Forbidden');
StatusError.NOT_FOUND = new StatusError(404,'Not found');
StatusError.CONFLICT = new StatusError(409,'Conflict');
StatusError.SERVER_INTERNAL = new StatusError(500,'Server Internal');

StatusError.uniqueConflict = function(originError) {
  const err = new StatusError(409, 'conflict');
  err.fields = originError.fields;
  return err;
}

StatusError.from = function(err) {
  if (err instanceof StatusError) {
    return err;
  } else if (err instanceof SyntaxError) {
    return StatusError.BAD_REQUEST;
  } else if (err instanceof sequelize.UniqueConstraintError) {
    return StatusError.uniqueConflict(err);
  } else {
    return StatusError.SERVER_INTERNAL;
  }
}